package com.ikun.admin.common.config;

import com.ikun.admin.modules.auth.filter.AuthFilter;
import com.ikun.admin.modules.auth.filter.LoginFilter;
import com.ikun.admin.modules.auth.service.LoginOutService;
import com.ikun.admin.modules.auth.utils.UnauthEntryPoint;
import com.ikun.admin.websocket.constant.WebSocketConstant;
import com.ikun.common.manager.RedisManager;
import com.ikun.starters.jwt.IJwtMemberDataService;
import com.ikun.starters.jwt.ITokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author ximeng
 * @title: SecurityConfig
 */
@SpringBootConfiguration
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UnauthEntryPoint unauthEntryPoint;

    @Autowired
    private LoginOutService loginOutService;

    @Autowired
    private ITokenService tokenService;

    @Autowired
    private IJwtMemberDataService jwtMemberDataService;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RedisManager redisManager;

    @Value("${starters.jwt.token-key}")
    private String tokenKey;

    /**
     * 配置设置
     *
     * @param http
     * @throws Exception
     */
    //设置退出的地址和token
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
                .antMatchers("/ikun"+ WebSocketConstant.WEBSOCKET_URL+"/**").permitAll() //todo ！！！ 允许未认证的WebSocket连接
                .anyRequest().authenticated() // 其他请求需要认证
                .and()
                .cors()
                .and()
                .csrf()
                .disable();

        http.exceptionHandling()
                .authenticationEntryPoint(unauthEntryPoint)
                .and()
                .authorizeRequests()
//                .anyRequest().authenticated()//所有请求都需要认证
                .and().logout().logoutUrl("/sys/user/logout")
                .addLogoutHandler(loginOutService).and()
                .addFilter(new LoginFilter(authenticationManager(), tokenService, redisManager))
                .addFilter(new AuthFilter(authenticationManager(), tokenService, jwtMemberDataService, redisManager, tokenKey)).httpBasic();
    }

    /**
     * 加密器
     * @param auth
     * @throws Exception
     */
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder);
    }

    /**
     * 放行路径
     *
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {

        //不需要认证路径
        web.ignoring().antMatchers("/noAuth/**");
        //忽略webSocket路径
        web.ignoring().antMatchers(WebSocketConstant.WEBSOCKET_URL+"/**");
        //接口文档路径
        web.ignoring().antMatchers("/swagger-ui.html",
                "/swagger-ui/*",
                "/swagger-resources/**",
                "/v2/api-docs",
                "/v3/api-docs",
                "/webjars/**");


    }


}
